package com.huangd.platform.listener;

import com.huangd.platform.config.GlobalConfig;
import com.huangd.platform.common.utils.DownloadService;
import com.huangd.platform.config.Config;
import com.huangd.platform.enums.Deployment;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.io.File;
import java.io.IOException;


@WebListener
public class PlatformStartListener implements ServletContextListener {

	@Value("${file.address}")
	private String address;

	@Value("${huangd.deployment}")
	private String deployment;

	@Override
	public void contextDestroyed(ServletContextEvent event) {

		DownloadService.getInstance().destroy();
	}

	@Override
	public void contextInitialized(ServletContextEvent event) {

		GlobalConfig.TOMCAT_DIR = address;

		GlobalConfig.WEB_ROOT_DIR = address;

		GlobalConfig.DATA_WEB_ROOT_DIR = confirmDirExists(new File(GlobalConfig.WEB_ROOT_DIR).getParentFile().getAbsolutePath(), "platform_dynamic_data");
		GlobalConfig.DATA_PRESENTS = confirmDirExists(GlobalConfig.DATA_WEB_ROOT_DIR, "presents");
		GlobalConfig.DATA_UPLOAD_VERSIONS = confirmDirExists(GlobalConfig.DATA_WEB_ROOT_DIR, "upload_versions");
		GlobalConfig.DATA_UPLOAD_VERSIONS_CLIENT = confirmDirExists(GlobalConfig.DATA_UPLOAD_VERSIONS, "client");
		GlobalConfig.DATA_UPLOAD_VERSIONS_SERVER = confirmDirExists(GlobalConfig.DATA_UPLOAD_VERSIONS, "server");

		GlobalConfig.DATA_FILE_SYSTEM = GlobalConfig.DATA_WEB_ROOT_DIR;

		GlobalConfig.DATA_LOG_INSTALL = confirmDirExists(GlobalConfig.DATA_WEB_ROOT_DIR, "install");
		GlobalConfig.DATA_LOG_GAMESERVER = confirmDirExists(GlobalConfig.DATA_WEB_ROOT_DIR, "gameserver");

		GlobalConfig.DATA_LOG_GAME = confirmDirExists(GlobalConfig.DATA_WEB_ROOT_DIR, "game");

		GlobalConfig.DATA_WEB_LOGGER_DATA = confirmDirExists(GlobalConfig.DATA_WEB_ROOT_DIR, "logger/data/");
		GlobalConfig.DATA_WEB_EXCEL_DATA = confirmDirExists(GlobalConfig.DATA_WEB_ROOT_DIR, "excel/");
		GlobalConfig.DATA_WEB_ANALYZE_CACHE = confirmDirExists(GlobalConfig.DATA_WEB_ROOT_DIR, "analyze_cache/");
		try {
			File f = new File(GlobalConfig.DATA_WEB_ROOT_DIR, "rsync_data_log_time.txt");
			if (f.exists()) {
				GlobalConfig.LAST_RSYNC_DATA_LOG_TIME = FileUtils.readFileToString(f);
			}


			Config.deployment = Deployment.valueOf(deployment);
		} catch (Exception e) {
			e.printStackTrace();
		}

		File downloadTmpDir = new File(GlobalConfig.DATA_WEB_EXCEL_DATA, "tmp");
		try {
			FileUtils.deleteDirectory(downloadTmpDir);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private String confirmDirExists(String parent, String name) {

		File dir = new File(parent, name);
		if (!dir.exists())
			dir.mkdirs();

		return dir.getAbsolutePath() + File.separator;
	}
}
